<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入帖子标题"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="圈子" prop="topicId">
        <el-select v-model="queryParams.topicId" placeholder="所属圈子" clearable style="width: 240px">
          <el-option
            v-for="item in topicOptions"
            :key="item.topicId"
            :label="item.topicName"
            :value="item.topicId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="帖子状态" clearable style="width: 240px">
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:post:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:post:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="帖子ID" align="center" prop="postId" v-if="columns[0].visible" />
      <el-table-column label="标题" align="center" prop="title" v-if="columns[1].visible" :show-overflow-tooltip="true" />
      <el-table-column label="圈子" align="center" prop="topicName" v-if="columns[2].visible" :show-overflow-tooltip="true" />
      <el-table-column label="发布者" align="center" prop="userName" v-if="columns[3].visible" :show-overflow-tooltip="true" />
      <el-table-column label="阅读数" align="center" prop="readCount" v-if="columns[4].visible" width="80" />
      <el-table-column label="点赞数" align="center" prop="likeCount" v-if="columns[5].visible" width="80" />
      <el-table-column label="评论数" align="center" prop="commentCount" v-if="columns[6].visible" width="80" />
      <el-table-column label="精华" align="center" v-if="columns[7].visible" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isFeatured"
            active-value="1"
            inactive-value="0"
            @change="handleFeaturedChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="置顶" align="center" v-if="columns[8].visible" width="80">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isSticky"
            active-value="1"
            inactive-value="0"
            @change="handleStickyChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" v-if="columns[9].visible" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns[10].visible" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:post:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 查看帖子详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <div class="post-detail">
        <h2 class="post-title">{{ form.title }}</h2>
        <div class="post-meta">
          <span>作者：{{ form.userName }}</span>
          <span>圈子：{{ form.topicName }}</span>
          <span>发布时间：{{ parseTime(form.createTime) }}</span>
        </div>
        <div class="post-content" v-html="form.content"></div>
        <div class="post-media" v-if="form.media && form.media.length > 0">
          <h3>媒体文件</h3>
          <div class="media-list">
            <template v-for="(item, index) in form.mediaList">
              <el-image 
                v-if="item.type === 'image'"
                :key="index"
                style="width: 150px; height: 150px; margin: 5px;"
                :src="item.url" 
                :preview-src-list="getImagePreviewList()"
              ></el-image>
              <video 
                v-else-if="item.type === 'video'"
                :key="index"
                style="width: 300px; margin: 5px;"
                :src="item.url" 
                controls
              ></video>
            </template>
          </div>
        </div>
        <div class="post-stats">
          <el-tag type="info">阅读数：{{ form.readCount }}</el-tag>
          <el-tag type="success">点赞数：{{ form.likeCount }}</el-tag>
          <el-tag type="warning">评论数：{{ form.commentCount }}</el-tag>
          <el-tag type="danger" v-if="form.isFeatured === '1'">精华</el-tag>
          <el-tag type="danger" v-if="form.isSticky === '1'">置顶</el-tag>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="open = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPost, getPost, delPost, changePostStatus, toggleFeatured, toggleSticky } from "@/api/quanzi/post";
import { listTopic } from "@/api/quanzi/topic";

export default {
  name: "Post",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 帖子表格数据
      postList: [],
      // 圈子选项
      topicOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        topicId: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 列信息
      columns: [
        { key: 0, label: `帖子ID`, visible: true },
        { key: 1, label: `标题`, visible: true },
        { key: 2, label: `圈子`, visible: true },
        { key: 3, label: `发布者`, visible: true },
        { key: 4, label: `阅读数`, visible: true },
        { key: 5, label: `点赞数`, visible: true },
        { key: 6, label: `评论数`, visible: true },
        { key: 7, label: `精华`, visible: true },
        { key: 8, label: `置顶`, visible: true },
        { key: 9, label: `状态`, visible: true },
        { key: 10, label: `创建时间`, visible: true }
      ]
    };
  },
  created() {
    // 如果是从圈子管理跳转过来，设置默认圈子ID
    if (this.$route.query.topicId) {
      this.queryParams.topicId = this.$route.query.topicId;
      if (this.$route.query.topicName) {
        this.title = this.$route.query.topicName + " - 帖子管理";
      } else {
        this.title = "帖子管理";
      }
    } else {
      this.title = "帖子管理";
    }
    
    this.getList();
    this.getTopicOptions();
  },
  methods: {
    /** 查询帖子列表 */
    getList() {
      this.loading = true;
      listPost(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.postList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询圈子选项 */
    getTopicOptions() {
      listTopic({ pageSize: 100 }).then(response => {
        this.topicOptions = response.rows;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      // 如果是从圈子管理跳转过来，保留圈子ID
      if (this.$route.query.topicId) {
        this.queryParams.topicId = this.$route.query.topicId;
      }
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.postId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 查看按钮操作 */
    handleView(row) {
      this.form = {};
      const postId = row.postId || this.ids;
      getPost(postId).then(response => {
        this.form = response.data;
        // 处理媒体文件
        if (this.form.media) {
          try {
            this.form.mediaList = JSON.parse(this.form.media);
          } catch (e) {
            this.form.mediaList = [];
          }
        } else {
          this.form.mediaList = [];
        }
        this.open = true;
        this.title = "查看帖子详情";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const postIds = row.postId || this.ids;
      this.$modal.confirm('是否确认删除帖子编号为"' + postIds + '"的数据项？').then(function() {
        return delPost(postIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/post/export', {
        ...this.queryParams
      }, `post_${new Date().getTime()}.xlsx`);
    },
    // 帖子状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.title + '"帖子吗？').then(function() {
        return changePostStatus(row.postId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    // 精华状态修改
    handleFeaturedChange(row) {
      let text = row.isFeatured === "1" ? "设为精华" : "取消精华";
      this.$modal.confirm('确认要"' + text + '""' + row.title + '"帖子吗？').then(function() {
        return toggleFeatured(row.postId, row.isFeatured);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.isFeatured = row.isFeatured === "1" ? "0" : "1";
      });
    },
    // 置顶状态修改
    handleStickyChange(row) {
      let text = row.isSticky === "1" ? "置顶" : "取消置顶";
      this.$modal.confirm('确认要"' + text + '""' + row.title + '"帖子吗？').then(function() {
        return toggleSticky(row.postId, row.isSticky);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.isSticky = row.isSticky === "1" ? "0" : "1";
      });
    },
    // 获取图片预览列表
    getImagePreviewList() {
      if (!this.form.mediaList) {
        return [];
      }
      return this.form.mediaList
        .filter(item => item.type === 'image')
        .map(item => item.url);
    }
  }
};
</script>

<style scoped>
.post-detail {
  padding: 20px;
}
.post-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 15px;
}
.post-meta {
  color: #666;
  margin-bottom: 20px;
}
.post-meta span {
  margin-right: 15px;
}
.post-content {
  margin-bottom: 20px;
  line-height: 1.6;
}
.post-media {
  margin-bottom: 20px;
}
.media-list {
  display: flex;
  flex-wrap: wrap;
}
.post-stats {
  margin-top: 20px;
}
.post-stats .el-tag {
  margin-right: 10px;
}
</style>